from imaplib import *
from django.conf import settings
from django.contrib.auth.models import User

import re
import email

box_cutter = re.compile('(?P<flags>\(.+\)) (?P<delim>"/") "(?P<name>[\w]+)"')

def login_user(request):
    if not 'username' in request.POST or not 'password' in request.POST:
        return False
    user = request.POST['username']
    passwd = request.POST['password']
    mailbox = 'INBOX'
    
    server = imap_login(user, passwd)
    
    if server:
        from django.contrib.auth import authenticate, login
        dj_user = authenticate(username="IMAP_%s" % user, password=passwd)
        if not dj_user:
            User.objects.create_user("IMAP_%s" % user, '', passwd)
            dj_user = authenticate(username="IMAP_%s" % user, password=passwd)
        if dj_user:
            login(request, user)
        mboxes = server.list()[1]
        mail_boxes = parse_mboxes(mboxes)
        messages = get_messages(mailbox, server)
        server.logout()
        return (mail_boxes, messages)
    else:
        return False

def imap_login(user, passwd):
    try:
        server = IMAP4_SSL(settings.EMAIL_SERVER)
        server.login(user,passwd)
        return server
    except IMAP4.error:
        server.logout()
        return False

def parse_mboxes(mboxes):                                                       
    parsed_box_list = []                                                        
    for box in mboxes:                                                          
        parsed_box_list.append(box_cutter.match(box).groupdict())               
    return parsed_box_list

def get_messages(mailbox, server):
    message_list = []
    server.select(mailbox)
    r, data = server.search(None, 'ALL')
    for msg in data[0].split():
        r, data = server.fetch(msg, '(BODY[HEADER.FIELDS (SUBJECT FROM DATE TO CC BCC IN-REPLY-TO REFERENCES )])' ) 
        message_list.append(email.message_from_string(data[0][1].decode('quopri_codec')))
        #print 'Message %s\n%s\n' % (msg, data[0][1])
    return message_list
